package cn.h8k.hj212.starter.autoconfigure;

import cn.h8k.hj212.codec.EnhancedHj212Codec;
import cn.h8k.hj212.codec.Hj212EntityCodec;
import cn.h8k.hj212.codec.Hj212Validator;
import cn.h8k.hj212.codec.impl.DefaultHj212EntityCodec;
import cn.h8k.hj212.codec.impl.DefaultHj212Validator;
import cn.h8k.hj212.config.Hj212Config;
import cn.h8k.hj212.factory.Hj212EntityCodecFactory;
import cn.h8k.hj212.plugin.PluginManager;
import cn.h8k.hj212.plugin.impl.AtmosphericFactorPlugin;
import cn.h8k.hj212.version.ProtocolVersion;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * HJ212协议增强自动配置类
 * 支持插件化、缓存、版本适配等高级功能
 * 
 * @author H8K Team
 * @since 1.0
 */
@Configuration
@ConditionalOnClass({Hj212EntityCodec.class})
@EnableConfigurationProperties(Hj212Properties.class)
public class Hj212AutoConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(Hj212AutoConfiguration.class);

    private final Hj212Properties properties;

    public Hj212AutoConfiguration(Hj212Properties properties) {
        this.properties = properties;
    }

    /**
     * 初始化插件
     */
    @PostConstruct
    public void initializePlugins() {
        if (properties.getPlugin().isEnabled() && properties.getPlugin().isAutoRegisterDefaults()) {
            try {
                PluginManager pluginManager = PluginManager.getInstance();
                
                // 注册默认的大气环境监测因子插件
                if (pluginManager.getAllPlugins().isEmpty()) {
                    pluginManager.registerPlugin(new AtmosphericFactorPlugin());
                    logger.info("自动注册默认插件: AtmosphericFactorPlugin");
                }
            } catch (Exception e) {
                logger.warn("自动注册默认插件失败", e);
            }
        }
    }

    /**
     * 创建HJ212配置对象
     */
    @Bean
    @ConditionalOnMissingBean
    public Hj212Config hj212Config() {
        Hj212Config config = new Hj212Config();
        
        // 缓存配置
        config.setEnableCache(properties.getCache().isEnabled());
        config.setCacheSize(properties.getCache().getSize());
        config.setCacheTtl(properties.getCache().getTtl());
        
        // 验证配置
        config.setEnableValidation(properties.getValidation().isEnabled());
        config.setEnableLengthValidation(properties.getValidation().isLength());
        config.setEnableCrcValidation(properties.getValidation().isCrc());
        
        // 插件配置
        config.setEnablePlugins(properties.getPlugin().isEnabled());
        
        // 版本配置
        config.setDefaultVersion(properties.getVersion().getProtocolVersion());
        
        // 自定义属性
        properties.getCustom().forEach(config::setCustomProperty);
        
        logger.info("HJ212配置创建完成: 缓存={}, 验证={}, 插件={}, 版本={}", 
                   config.isEnableCache(), config.isEnableValidation(), 
                   config.isEnablePlugins(), config.getDefaultVersion().getFullName());
        
        return config;
    }

    /**
     * 创建HJ212校验器
     */
    @Bean
    @ConditionalOnMissingBean
    public Hj212Validator hj212Validator() {
        return new DefaultHj212Validator(
            properties.getValidation().isLength(), 
            properties.getValidation().isCrc()
        );
    }

    /**
     * 创建增强的HJ212实体类编解码器（默认）
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "hj212.codec.type", havingValue = "enhanced", matchIfMissing = true)
    public Hj212EntityCodec enhancedHj212EntityCodec(Hj212Config config) {
        logger.info("创建增强HJ212编解码器");
        return new EnhancedHj212Codec(
            config.isEnableCache(),
            config.isEnableValidation(),
            config.getDefaultVersion()
        );
    }

    /**
     * 创建默认的HJ212实体类编解码器
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "hj212.codec.type", havingValue = "default")
    public Hj212EntityCodec defaultHj212EntityCodec(Hj212Validator validator) {
        logger.info("创建默认HJ212编解码器");
        return new DefaultHj212EntityCodec(validator);
    }

    /**
     * 创建高性能HJ212实体类编解码器
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "hj212.codec.type", havingValue = "high-performance")
    public Hj212EntityCodec highPerformanceHj212EntityCodec() {
        logger.info("创建高性能HJ212编解码器");
        return Hj212EntityCodecFactory.createHighPerformanceCodec();
    }

    /**
     * 创建兼容模式HJ212实体类编解码器
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "hj212.codec.type", havingValue = "compatibility")
    public Hj212EntityCodec compatibilityHj212EntityCodec() {
        logger.info("创建兼容模式HJ212编解码器");
        return Hj212EntityCodecFactory.createCompatibilityCodec();
    }

    /**
     * 创建测试用HJ212实体类编解码器
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "hj212.codec.type", havingValue = "test")
    public Hj212EntityCodec testHj212EntityCodec() {
        logger.info("创建测试用HJ212编解码器");
        return Hj212EntityCodecFactory.createTestCodec();
    }

    /**
     * 创建插件管理器Bean
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "hj212.plugin.enabled", havingValue = "true", matchIfMissing = true)
    public PluginManager pluginManager() {
        logger.info("创建插件管理器");
        return PluginManager.getInstance();
    }
}
